package com.bruce.ai.alibaba.vectorstore.redis.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/redis")
public class RedisController {

    private static final Logger logger = LoggerFactory.getLogger(RedisController.class);
    private final RedisVectorStore redisVectorStore;

    @Autowired
    public RedisController(@Qualifier("redisVectorStoreCustom") RedisVectorStore redisVectorStore) {
        this.redisVectorStore = redisVectorStore;
    }

    @GetMapping("/import")
    public void importData(@RequestParam(value = "messages", defaultValue = "Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!") String messages,
    @RequestParam(value = "owerName",defaultValue = "bruce") String owerName) {
        logger.info("start import data");
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "12345");
        map.put("year", "2025");
        map.put("name", owerName);
        List<Document> documents = List.of(
                new Document(messages,map));
        redisVectorStore.add(documents);
    }

    @GetMapping("/search")
    public List<Document> search(@RequestParam(value = "query",defaultValue = "Spring AI") String query) {
        logger.info("start search data");
        return redisVectorStore.similaritySearch(SearchRequest
                .builder()
                .query(query)
                .topK(2)
                .build());
    }

    @GetMapping("delete-filter")
    public void searchFilter(@RequestParam(value = "owerName",defaultValue = "bruce") String owerName) {
        logger.info("start delete data with filter");
        FilterExpressionBuilder b = new FilterExpressionBuilder();
        Filter.Expression expression = b.eq("name", owerName).build();

        redisVectorStore.delete(expression);
    }
}
